<?php
/**
 * Created by PhpStorm.
 * User: yuanluke
 * Date: 4/21/17
 * Time: 14:44
 */

namespace App\Http\Utils\WechatTrait;

use EasyWeChat\Payment\Order;
use Log;
use ErrorException;

trait WeChatPaymentTrait {

    /**
     * 调起微信支付
     * @param $body
     * @param $detail
     * @param $ordernum
     * @param $money
     * @param $openid
     * @param $url
     * @return array
     * @throws ErrorException
     */
    public function weChatPayment($body,$detail,$ordernum,$money,$openid,$url){
        try {
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            
            //调取微信支付
            //1.创建微信订单
            $attributes = [
                'trade_type' => 'JSAPI',
                'body' => $body,
                'detail' => $detail,
                'out_trade_no' => $ordernum,
                'total_fee' => $money,
                'notify_url'=>$url,
                'openid' => $openid
            ];
            $order = new Order($attributes);
            //统一下单接口
            $result = app('wechat')->payment->prepare($order);
            $config = array();
            Log::debug($result);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
                $prepayId = $result->prepay_id;
                $config = app('wechat')->payment->configForJSSDKPayment($prepayId); // 返回数组
            } else {
                return ['code' => -1];//调用失败
            }
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code' => 1, 'data' => $config];//已成功调用微信支付
        }catch(ErrorException $ex){
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
            return ['code' => -1];//调用失败
        }
    }
}